<?php
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Cache;
use app\common\library\Letter;
class Vod extends Model{
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
	// 自动完成
	protected $auto = [];
	protected $insert = ['vod_addtime'];
	protected $update = [];
	
	//自动获取VodIsendTextAttr
    public function getVodIsendTextAttr($value,$data){
        $serialize = [0=>'连载',1=>'完结'];
        return $serialize[$data['vod_isend']];
    }	
	//自动完成相关字段
	protected function setVodAddtimeAttr($value,$data){
		if (!empty($data['vod_checktime']) || empty($value)) {
			return time();
		}else{
			return strtotime($value);
		}
	}
	protected function setVodTagAttr($value,$data){
		if(empty($value) && !empty($data['auto_tag'])){
			return zanpian_get_tag($data['vod_name'],$data['vod_content']);
		}else{
			return $value;
		}
	}
	protected function setVodMcidAttr($value,$data){
		if(!empty($value)){
			if(is_array($value)){
				return implode(',', $value);
			}else{
			    return $value;
			}
		}elseif(!empty($data['vod_mcid_name'])){
			return model('Mcat')->get_mcid($data['vod_cid'],$data['vod_mcid_name']);
		}elseif(!empty($data['vod_keywords'])){
			return model('Mcat')->get_mcid($data['vod_cid'],$data['vod_keywords']);
		}else{
			return '';
		}
	}
    protected function setVodPrtyAttr($value){
        if(!is_array($value)){
            return 0;
        }else{
            $attribute = 0;
            foreach ($value as $key=>$value){
                $attribute += $value;
            }
            return $attribute;
        }
    }
    protected function setVodWeekdayAttr($value){
        if(!is_array($value)){
            return 0;
        }else{
            $attribute = 0;
            foreach ($value as $key=>$value){
                $attribute += $value;
            }
            return $attribute;
        }
    }	
	protected function setVodPlayAttr($value,$data){
		if(!empty($value)){
			$play_list=$this->vod_url_check($value, $data['vod_url']);
			return $play_list['vod_play'];
		}
	}	
	protected function setVodUrlAttr($value,$data){
		if(!empty($value)){
			$play_list=$this->vod_url_check($data['vod_url'], $value);
			return $play_list['vod_url'];
		}
	}	
	protected function setVodLetterAttr($value,$data){
		$Letter = new Letter();
		if ($data['vod_name']) {
			return $Letter->getletter($data['vod_name']);
		}
	}
    protected function setVodLettersAttr($value,$data){
	    $Letter = new Letter();
	    if(empty($value)) {
		     return $Letter->getletters(trim($data['vod_name']),1);
		}else{
		    return trim($value);
		}
    }
	protected function setVodPicAttr($value){
		$img = model('Img');
		$file=$img->down_load(trim($value),'vod');
		return $file['file'];
	}
	protected function setVodPicThumbAttr($value){
		$img = model('Img');
		$file=$img->down_load(trim($value),'vod');
		return $file['file'];
	}	
	protected function setVodBigpicAttr($value){
		$img = model('Img');
		$file=$img->down_load(trim($value),'vod');
		return $file['file'];
	}
	protected function setVodContentAttr($value){	
	    if(!empty($value)){
	       return zanpian_content_down_images(trim($value),'vod');
	    }else{
	       return ''; 	 
	    }
	}
	protected function setVodTvexpAttr($value){	
	    if(!empty($value)){
	         return zanpian_content_down_images(trim($value),'vod');
	    }else{
		     return ''; 
		}
	}	
	protected function setVodGoldAttr($value){
		if($value > 10){
			$value = 10;
		}	
		return 	$value;
	}	
	protected function setVodFilmtimeAttr($value){
		if ($value) {
			return strtotime($value.' 0:0:0');
		}else{
			return '';
		}
	}	
	protected function setVodkeywordsAttr($value,$data){
		if(!empty($value)){
			    return $value;
		}elseif(empty($value) &&  !empty($data['vod_name']) && !empty($data['auto_keywords'])){
			$get=controller('get');
			$info=$get->keywords($data['vod_name'],1);
			if($info['code']=1){
			    return $info['data']['str'];	
			}else{
				return '';
			}
		}else{
			return '';
		}
	}
	protected function setVodActorAttr($value){	
	    if(!empty($value)){
	       return format_text($value);
	    }else{
		   return ''; 
		}
	}
	protected function setVodDirectorAttr($value){	
	    if(!empty($value)){
	        return format_text($value);
	    }else{
		    return ''; 
		}
	}
	//事件注册
    protected static function init(){
		//写入后置事件
		Vod::afterWrite(function ($vod){
			if(!empty($vod->vod_id)){
			   model('Manage')->DelCache(1,$vod->vod_id);
			}
			if(!empty($vod->vod_mcid)){				
			    model('Mcid')->mcid_updata($vod->vod_id,1,$vod->vod_mcid);
			}
			if(!empty($vod->vod_tag)){
			    model('Tag')->tag_updata($vod->vod_id,1,$vod->vod_tag);
			}	  
			if(!empty($vod->vod_diantai)){			
			   model('Vodtv')->tv_updata($vod->vod_id,1,$vod->vod_diantai);
            }			   
			if(!empty($vod->vod_actor)){			
			   model('Actors')->actors_updata($vod->vod_id,1,$vod->vod_actor);
			}
			if(!empty($vod->vod_director)){			
			   model('Actors')->actors_updata($vod->vod_id,2,$vod->vod_director);
			}
			if(!empty($vod->vod_reurl)){			
			   model('Urls')->urls_updata($vod->vod_id,$vod->vod_reurl);
			}
		});
		//删除后置事件
        Vod::afterDelete(function ($vod){
			$upload=config('upload');
			zanpian_del_img_file($vod->vod_content);
			zanpian_del_img_file($vod->vod_tvexp);
			//删除图片和缩略图
            if(!empty($vod->vod_pic) && file_exists(ROOT_PATH.$vod->vod_pic)){
                @unlink(ROOT_PATH.$vod->vod_pic);
			    if (!empty($upload['upload_thumb_size']) && !empty($upload['upload_thumb'])) {
				    $thumbs = explode(',', $upload['upload_thumb_size']);
				    foreach($thumbs as $k => $v){
						$img_path=ROOT_PATH.$vod->vod_pic.'_'.$v.'.'.strtolower(pathinfo($vod->vod_pic, PATHINFO_EXTENSION));
                        if(file_exists($img_path)){
                            @unlink($img_path);
                        }					
				    }
			    }				
            }
            if(!empty($vod->vod_pic_thumb) && file_exists(ROOT_PATH.$vod->vod_pic_thumb)){
                @unlink(ROOT_PATH.$vod->vod_pic_thumb);
            }
            if(!empty($vod->vod_bigpic) && file_exists(ROOT_PATH.$vod->vod_bigpic)){
                @unlink(ROOT_PATH.$vod->vod_bigpic);
            }
			db('story')->where('story_vid',$vod->vod_id)->delete();
			db('part')->where('part_vid',$vod->vod_id)->delete();
			db('actor')->where('actor_vid',$vod->vod_id)->delete();
			db('role')->where('role_vid',$vod->vod_id)->delete();
            db('Tag')->where(['tag_id'=>$vod->vod_id,'tag_sid'=>1])->delete();
            db('Mcid')->where(['mcid_id'=>$vod->vod_id,'mcid_sid'=>1])->delete();			
            db('Vodtv')->where(['vodtv_id'=>$vod->vod_id,'vodtv_sid'=>1])->delete();
			db('Actors')->where('actors_id',$vod->vod_id)->delete();
			db('Urls')->where('urls_id',$vod->vod_id)->delete();
			db('Gold')->where('gold_vid',$vod->vod_id)->delete();
			db('topic')->where(['topic_did'=>$vod->vod_id,'topic_sid'=>1])->delete();			
			db('playlog')->where('log_vid',$vod->vod_id)->delete();
			db('cm')->where(['cm_vid'=>$vod->vod_id,'cm_sid'=>1])->delete();
			db('favorite')->where('favorite_vid',$user->user_id)->delete();
			db('remind')->where('remind_vid',$user->user_id)->delete();
            model('Manage')->DelCache(1,$vod->vod_id);			
       });	
    }			
   //关联相关表
	public function story(){
		return $this->hasOne('Story','story_vid');
    }
	public function actor(){
        return $this->hasOne('Actor','actor_vid');
    }   
	public function role(){
        return $this->hasMany('Role','role_vid')->order('role_oid asc');
    }
	public function news(){
        return $this->hasMany('topic','topic_did')->where(['topic_sid'=>1,'topic_tsid'=>2]);
    }
	public function vod(){
        return $this->hasMany('topic','topic_did')->where(['topic_sid'=>1,'topic_tsid'=>1]);
    }	
	public function part(){
        return $this->hasMany('part','part_vid')->order('part_oid asc');
    }
	public function theme(){
        return $this->hasMany('theme','theme_vid');
    }
	public function lines(){
        return $this->hasMany('lines','lines_vid');
    }
	public function music(){
        return $this->hasMany('music','music_vid');
    }
	//验证播放地址
	function vod_url_check($vod_play,$vod_url){
		$playarray = is_array($vod_play)?$vod_play:explode('$$$',$vod_play);
		$urlarray = is_array($vod_url)?$vod_url:explode('$$$',$vod_url);
		$new_play = array();
		$new_url = array();
		foreach($playarray as $key=>$value){
			if(empty($urlarray[$key]) || empty($value)){
				
				  continue;
			}			
			$new_play[$key]=$value;
			$arr_ji = explode(chr(13),str_replace(array("\r\n", "\n", "\r"), chr(13),$urlarray[$key]));
			foreach($arr_ji as $k=>$value){
			    $urlji = explode('$',$value);
			    if(count($urlji) > 1 ){
				    $new_url[$key][$k] = $value;
			    }else{
				    $new_url[$key][$k] = trim($urlji[0]);
			    }
		    }
			$new_url[$key]=implode(chr(13),$new_url[$key]);
		}
		return array('vod_play'=>implode('$$$',$new_play),'vod_url'=>implode('$$$',$new_url));
	}

    public function listData($tag){
		$param = zanpiancms_param_url();
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['field']= !empty($tag['field']) ? $tag['field'] : 'vod_id,vod_cid,vod_mcid,vod_name,vod_aliases,vod_title,vod_color,vod_actor,vod_director,vod_content,vod_pic,vod_bigpic,vod_diantai,vod_tvcont,vod_tvexp,vod_area,vod_language,vod_year,vod_continu,vod_total,vod_isend,vod_addtime,vod_hits,vod_hits_day,vod_hits_week,vod_hits_month,vod_hits_lasttime,vod_stars,vod_up,vod_down,vod_play,vod_gold,vod_url,vod_golder,vod_isfilm,vod_filmtime,vod_length,vod_weekday,vod_letters,vod_bigpic,vod_label,vod_jumpurl,vod_prty';
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : 10;
        if(!empty($tag['page']) && !empty($param['order'])){
			$tag['order']='vod_'.$param['order'].' desc';
		}			
		if(empty(order_check($tag['order']))){
			$tag['order']='vod_addtime desc';
		}	
		$cahce=tag_cache($tag);
	    //优先从缓存调用数据及分页变量
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){			
			$data_cache_content = Cache::get($cahce['cache_name']);
			if($data_cache_content){
				return $data_cache_content;
			}
		}		
		$where=[];
		//$where['story_status']=['eq',1];
		//$where['actor_status']=['eq',1];
	    if(!empty($tag['ids'])){
		    $ids = explode(',',$tag['ids']);
		    if(count($ids)>1) {
			    $where['vod_id'] = array('in',$tag['ids']);
		    }else{
			    $where['vod_id'] = array('eq',$ids[0]);
		    }
	    }		
	    if(!empty($tag['not'])){
		     $where['vod_id'] = array('neq',$tag['not']);
	    }	
	    if (!empty($tag['letter'])) {
		    $letter = explode(',',$tag['letter']);
		    if(count($letter)>1) {
			    $where['vod_letter'] = array('in',$tag['letter']);
		    }else{
			    $where['vod_letter'] = array('eq',$letter[0]);
		    }
	    }		
	    if(!empty($tag['cid'])) {
		    $cids = explode(',',trim($tag['cid']));
		    if(count($cids) > 1) {
			    $where['vod_cid'] = array('in',getlistarr_tag($cids));
		    }else{
			     $where['vod_cid'] = getlistsqlin($tag['cid']);
		    }
	    }			
	    if(!empty($tag['name'])) {
			if(!is_array($tag['name'])){
		       $name = explode(',',$tag['name']);
			}else{
			   $name =$tag['name'];
			}
		    if(count($name)>1) {
			    $where['vod_name'] = array('in',$tag['name']);
		    }else{
			    $where['vod_name'] = array('eq',$name[0]);
		    }	
	    }
	    if(!empty($tag['aliases'])) {
		    $where['vod_aliases'] = array('like','%'.$tag['aliases'].'%');
	    }		
	    if(!empty($tag['likename'])) {
		    $where['vod_name'] = array('like',$tag['likename'].'%');
	    }		
	    if(!empty($tag['wd'])) {
		    $where['vod_name|vod_letters|vod_aliases|vod_actor|vod_keywords|vod_director|vod_tag'] = array('like','%'.$tag['wd'].'%');	
	    }
	    if (!empty($tag['play'])) {
		    $where['vod_play'] = array('like','%'.$tag['play'].'%');
	    }
	    if (!empty($tag['title'])) {
		    $where['vod_title'] = array('like','%'.$tag['title'].'%');
	    }
	    if (!empty($tag['yanyuan'])) {
		    $where['vod_actor|vod_director'] = array('like','%'.$tag['yanyuan'].'%');	
	    }
	    if(!empty($tag['isfilm'])){
		    $where['vod_isfilm'] = array('eq',$tag['isfilm']);
	    }
	    if(!empty($tag['filmtime'])){
			if($tag['filmtime']==1){
		        //$where['vod_filmtime'] = array('between',array(strtotime("-6 month",time()),time()));
				$where['vod_filmtime'] = array('elt',time());
			}else{
				$tjinfo=explode('|',trim($tag['filmtime']));
			    if($tjinfo[1]){
				    $where['vod_filmtime'] = array('between',array(intval($tjinfo[0]),intval($tjinfo[1])));
			    }else{
		            $where['vod_filmtime'] = array('gt', time());
			    }
			}
	    }		
	    if(!empty($tag['isend'])){
		    $where['vod_isend'] = array('eq',$tag['isend']);
	    }		
	    if (!empty($tag['area'])) {
		    $area = explode(',',$tag['area']);
		    if(count($area)>1) {
			    $where['vod_area'] = array('in',$tag['area']);
		    }else{
			    $where['vod_area'] = array('eq',$area[0]);
		    }
	    }
	    if(!empty($tag['language'])) {
		    $language = explode(',',$tag['language']);
		    if(count($language)>1) {
			    $where['vod_language'] = array('in',$tag['language']);
		    }else{
			    $where['vod_language'] = array('eq',$language[0]);
		    }
	    }
	    if(!empty($tag['year'])) {
		    $year = explode(',',$tag['year']);
		    if(count($year)>1) {
			    $where['vod_year'] = array('in',$tag['year']);
		    }else{
			    $where['vod_year'] = array('eq',$year[0]);
		    }
	    }
	    if(!empty($tag['stars'])) {
		     $where['vod_stars'] = array('in',$tag['stars']);
	    }	
	    if (!empty($tag['hits'])) {
		    $hits = explode(',',$tag['hits']);
		    if (count($hits) > 1) {
			    $where['vod_hits'] = array('between',$hits[0].','.$hits[1]);
		    }else{
			    $where['vod_hits'] = array('gt',$hits[0]);
		    }
	    }		
        if(!empty($tag['gold'])) {
		    $gold = explode(',',$tag['gold']);
		    if(count($gold) > 1) {
			    $where['vod_gold'] = array('between',$gold[0].','.$gold[1]);
		    }else{
			    $where['vod_gold'] = array('gt',$gold[0]);
		    }
	    }		
	    if(!empty($tag['golder'])) {
		    $golder = explode(',',$tag['golder']);
		    if(count($golder) > 1) {
			    $where['vod_golder'] = array('between',$golder[0].','.$golder[1]);
		    }else{
			    $where['vod_golder'] = array('gt',$golder[0]);
		    }
	    }	
	    if(!empty($tag['up'])) {
		    $up = explode(',',$tag['up']);
		    if(count($up)>1) {
			    $where['vod_up'] = array('between',$up[0].','.$up[1]);
		    }else{
			    $where['vod_up'] = array('gt',$up[0]);
		    }
	    }		
	    if(!empty($tag['down'])) {
		    $down = explode(',',$tag['down']);
		    if(count($down)>1) {
			    $where['vod_down'] = array('between',$down[0].','.$down[1]);
		    }else{
			    $where['vod_down'] = array('gt',$down[0]);
		    }
	    }		
        if(!empty($tag['addtime'])){
		    $time = explode(',',$tag['addtime']);
		    if(count($time) > 1) {
			    $where['vod_addtime'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['vod_addtime'] = array('gt',intval(strtotime($time[0])));
		    }			
        }
	    if(!empty($tag['tj'])){
		    $tjinfo=explode('|',trim($tag['tj']));
		    if($tjinfo[3]){
			    $where[$tjinfo[3]] = array($tjinfo[1],$tjinfo[2]);
		    }else{
			    $where[$tjinfo[0]] = array($tjinfo[1],$tjinfo[2]);
		    }
		}
		if (!empty($tag['diantai'])) {
		    $where['vod_diantai'] = array('neq','');
	    }	
		if($tag['prty']){
			if($tag['prty']){
			    $where['vod_prty'] = $tag['prty'];
			}
		}
		if($tag['weekday']){
			if($tag['weekday']){
			    $where['vod_weekday'] = $tag['weekday'];
			}			
		}
        if(!empty($tag['tag'])){
		    $where['tag_name'] = array('eq',$tag['tag']);
		    $where['tag_sid'] = 1;
		    $rs = db('tag')->join('vod vod','vod.vod_id = tag_id','RIGHT');
	    }elseif(!empty($tag['mcid'])){
		    $mcid=explode(',',$tag['mcid']);
		    if(count($mcid)>1){
		        $where['mcid_mid']=array('in',$tag['mcid']);
				$rs = db('mcid')->join('vod vod','vod.vod_id = mcid_id','RIGHT')->group('mcid_id');	
		    }else{
		        $where['mcid_mid'] = array('eq',$tag['mcid']);
                $rs = db('mcid')->join('vod vod','vod.vod_id = mcid_id');					
		    }
/* 			if(empty($tag['page'])){
			    $limit_str = intval(abs($tag['start'])).",".intval(abs($tag['limit']));
			    $mcid_array=db('mcid')->where($mcid_where)->limit($limit_str)->column('mcid_id');
				$where['vod_id'] = array('in',$mcid_array);
			    $rs = db('vod');
		    }else{
				$where['mcid_mid']=$mcid_where['mcid_mid'];
				$rs = db('mcid')->join('vod vod','vod.vod_id = mcid_id','RIGHT')->group('mcid_id');	
			} */
				
        }elseif(!empty($tag['tv'])){
		    $tv=explode(',',$tag['tv']);
		    if(count($tv)>1){
		        $where['vodtv_name']=array('in',$tag['tv']);
		    }else{
		        $where['vodtv_name'] = array('eq',$tag['tv']);	
		    }
		    $rs = db('vodtv')->join('vod vod','vod.vod_id = vodtv_id','RIGHT')->group('vodtv_id');
	    }elseif(!empty($tag['actor'])){
            $actor=explode(',',$tag['actor']);
		    if(count($actor)>1){
			    $where['actors_name']=array('in',$tag['actor']);
				$rs = db('actors')->join('vod vod','vod.vod_id = actors_id')->group('actors_id');
			    //$where['actors_type']=1;
		    }else{
			    $where['actors_name'] = array('eq',$tag['actor']);
				$rs = db('actors')->join('vod vod','vod.vod_id = actors_id');
			   // $where['actors_type']=1;
		    }
			//$rs = db('vod')->join('actors actors','actors.actors_id = vod_id','LEFT');
	    }elseif(!empty($tag['director'])){
            $actor=explode(',',$tag['director']);
		    if(count($actor)>1){
			    $where['actors_name']=array('in',$tag['director']);
				$rs = db('actors')->join('vod vod','vod.vod_id = actors_id','RIGHT')->group('actors_id');
			    //$where['actors_type']=2;
		    }else{
			    $where['actors_name'] = array('eq',$tag['director']);
				$rs = db('actors')->join('vod vod','vod.vod_id = actors_id','RIGHT');
			   // $where['actors_type']=2;
		    }
		    
	    }elseif(!empty($tag['juqing']) && empty($tag['yanyuanbiao'])){
		    $rs=db('vod')->join('story story','story.story_vid = vod_id','LEFT');
	    }elseif(!empty($tag['yanyuanbiao']) && empty($tag['juqing'])){
		    $rs=db('vod')->join('actor actor','actor.actor_vid = vod_id','LEFT');
	    }elseif(!empty($tag['yanyuanbiao']) && !empty($tag['juqing'])){
		    $rs=db('vod')->join('story story','story.story_vid = vod_id','LEFT')->join('actor actor','actor.actor_vid = vod_id','LEFT');
	    }else{
		    $rs=db('vod');
		}
        $where['vod_status']=['eq',1];		
        if(!empty($tag['page'])){
			$url=urldecode(zanpian_list_url($GLOBALS['route'],config('params')));
		    $data = $rs->where($where)->field($tag['field'])->order($tag['order'])->paginate($tag['limit'],false,['path'=>$url]);
		}else{
			$limit_str = intval(abs($tag['start'])).",".intval(abs($tag['limit']));
			$data = $rs->where($where)->field($tag['field'])->order($tag['order'])->limit($limit_str)->select();
		}
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){
			cache::tag('foreach_vod')->set($cahce['cache_name'],$data,intval($cahce['cache_time'])); 
	    }
		return $data;
    } 

	
}
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------